<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>3.写个机器人-2</title>
	<link rel="stylesheet" href="./index.css">
</head>

<body>
<canvas id="canvas"></canvas>
<script id="vertex-shader-3d" type="x-shader/x-vertex">
uniform mat4 u_worldViewProjection;
uniform vec3 u_lightWorldPos;
uniform mat4 u_world;
uniform mat4 u_viewInverse;
uniform mat4 u_worldInverseTranspose;
uniform mat4 u_matrix;
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texcoord;

varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;

varying vec4 v_color;

attribute vec4 a_color;
void main() {
  v_texCoord = a_texcoord;
  v_position = (u_matrix * a_position);
  v_normal = (u_worldInverseTranspose * vec4(a_normal, 0)).xyz;
  v_surfaceToLight = u_lightWorldPos - (u_matrix * a_position).xyz;
  v_surfaceToView = (u_viewInverse[3] - (u_world * a_position)).xyz;
  gl_Position = v_position;
	v_color = a_color;

}
</script>
<script id="fragment-shader-3d" type="x-shader/x-fragment">
precision mediump float;

varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;

uniform vec4 u_lightColor;
uniform vec4 u_colorMult;
uniform sampler2D u_diffuse;
uniform vec4 u_specular;
uniform float u_shininess;
uniform float u_specularFactor;
uniform vec4 u_colorOffset;

varying vec4 v_color;
vec4 lit(float l ,//点光大小
float h,//高光大小
 float m) {
  return vec4(1.0,abs(l),(l > 0.0) ? pow(max(0.0, h), m) : 0.0,//如果有点光返回h或者0
              1.0);
}

void main() {
  vec4 diffuseColor = texture2D(u_diffuse, v_texCoord);//纹理
  vec3 a_normal = normalize(v_normal);//法线
  vec3 surfaceToLight = normalize(v_surfaceToLight);//光线到顶点向量
  vec3 surfaceToView = normalize(v_surfaceToView);//地对空方向
  vec3 halfVector = normalize(surfaceToLight + surfaceToView);//光线和法线中间值
  vec4 litR = lit(dot(a_normal, surfaceToLight),
                    dot(a_normal, halfVector), u_shininess);
  vec4 outColor = vec4((
  u_lightColor * (diffuseColor * litR.y * u_colorMult +//光线颜色和大小
                u_specular * litR.z * u_specularFactor)).rgb,//高光
      diffuseColor.a);//透明度
  gl_FragColor = outColor;
}
</script>
<script src="https://webglfundamentals.org/webgl/resources/webgl-utils.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/m4.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/primitives.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/texture-utils.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/chroma.min.js"></script>
<script>
const canvas = document.querySelector("#canvas");
const gl = canvas.getContext("webgl");

webglUtils.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

// Clear the canvas AND the depth buffer.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

gl.enable(gl.CULL_FACE);
gl.enable(gl.DEPTH_TEST);

//获取program,获取着色器变量
const program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
var programInfo = webglUtils.createProgramInfo(gl, ["vertex-shader-3d", "fragment-shader-3d"]);

const uniformSetters = webglUtils.createUniformSetters(gl, program);
const attribSetters  = webglUtils.createAttributeSetters(gl, program);
//获取模型
var buffers = window.primitives.createSphereBuffers(gl, 18, 48, 48);

const cubeBufferInfo   = primitives.createCubeWithVertexColorsBufferInfo(gl, 1);
//材质制作
var textures = textureUtils.makeStripeTexture(gl, { color1: "#FFF", color2: "#FFF", })

var TRS = function() {
	this.translation = [0, 0, 0];
	this.rotation = [0, 0, 0];
	this.scale = [1, 1, 1];
};

TRS.prototype.getMatrix = function(dst) {
	dst = dst || new Float32Array(16);
	var t = this.translation;
	var r = this.rotation;
	var s = this.scale;
	m4.translation(t[0], t[1], t[2], dst);
	m4.xRotate(dst, r[0], dst);
	m4.yRotate(dst, r[1], dst);
	m4.zRotate(dst, r[2], dst);
	m4.scale(dst, s[0], s[1], s[2], dst);
	return dst;
};

class three{
	static object(){
		const myObj={}
		myObj.children = [];
		myObj.localMatrix = m4.identity();
		myObj.worldMatrix = m4.identity();
		myObj.parent=null
		myObj.add = function(obj) {
			myObj.children.push(obj)
			obj.parent=myObj
		};

		myObj.translation = [0, 0, 0];
		myObj.rotation = [0, 0, 0];
		myObj.scale = [1, 1, 1];

		// myObj.transform=function(x=0,y=0,z=0){
		// 	m4.translate(myObj.localMatrix,x,y,z,myObj.localMatrix);
		// }
		// myObj.scale=function(x=1,y=1,z=1){
		// 	m4.scale(myObj.localMatrix,x,y,z,myObj.localMatrix);
		// }
		myObj.getMatrix = function(dst) {
			dst = dst || new Float32Array(16);
			var t = myObj.translation;
			var r = myObj.rotation;
			var s = myObj.scale;
			m4.translation(t[0], t[1], t[2], dst);
			m4.xRotate(dst, r[0], dst);
			m4.yRotate(dst, r[1], dst);
			m4.zRotate(dst, r[2], dst);
			m4.scale(dst, s[0], s[1], s[2], dst);
			return dst;
		};

		myObj.updateWorldMatrix = function() {//更新世界矩阵
			myObj.getMatrix(myObj.localMatrix)
			if (myObj.parent) {
				m4.multiply(myObj.parent.worldMatrix, myObj.localMatrix, myObj.worldMatrix);
			} else {
				m4.copy(myObj.localMatrix, myObj.worldMatrix);
			}
			myObj.children.forEach(function(child) {
				child.updateWorldMatrix();
			});
		};
		return myObj
	}
}
const obj= {
	name: "机器人关节",
	draw: false,
	children: [
		{
			name: "waist",
			translation: [0, 3, 0],
			children: [
				{
				name: "torso",
				translation: [0, 2, 0],
				children: [
					{
					name: "neck",
					translation: [0, 1, 0],
					children: [
						{
						name: "head",
						translation: [0, 1, 0],
						},
					],
					},
					{
					name: "left-arm",
					translation: [-1, 0, 0],
					children: [
						{
						name: "left-forearm",
						translation: [-1, 0, 0],
						children: [
							{
							name: "left-hand",
							translation: [-1, 0, 0],
							},
						],
						},
					],
					},
					{
					name: "right-arm",
					translation: [1, 0, 0],
					children: [
						{
						name: "right-forearm",
						translation: [1, 0, 0],
						children: [
							{
							name: "right-hand",
							translation: [1, 0, 0],
							},
						],
						},
					],
					},
				],
				},
				{
				name: "left-leg",
				translation: [-1, -1, 0],
				children: [
					{
					name: "left-calf",
					translation: [0, -1, 0],
					children: [
						{
						name: "left-foot",
						translation: [0, -1, 0],
						},
					],
					}
				],
				},
				{
				name: "right-leg",
				translation: [1, -1, 0],
				children: [
					{
					name: "right-calf",
					translation: [0, -1, 0],
					children: [
						{
						name: "right-foot",
						translation: [0, -1, 0],
						},
					],
					}
				],
				},
			],
		},
	],
};

const o={}
const objects=[]
const objectsToDraw=[]
function getC(nodeDescriptions){
    return nodeDescriptions ? nodeDescriptions.map(getObj) : [];
}
function getObj(obj){
	const node=three.object()
	o[obj.name]=node
	
    node.translation = obj.translation || node.translation;
	if (obj.draw !== false) {
      node.drawInfo = {
        uniforms: {
          u_colorOffset: [0, 0, 0.6, 0],
          u_colorMult: [.4, 0.4, 1.4, 1],
        },
        programInfo: programInfo,
        bufferInfo: cubeBufferInfo,
      };
      objectsToDraw.push(node.drawInfo);
      objects.push(node);
    }
	if(obj.children&&obj.children.length){
		getC(obj.children).forEach(temp=>{
			node.add(temp)
		})
	}
	return node
}
var scene =getObj(obj)
const nodeInfosByName=o
scene.scale=[5,5,5]
const camera={
	position:[0,0,100],
	target:[0,0,0],
	up:[0, 1, 0],
	matrix:m4.identity()
}

const model={
	radius: 100,
	position:[0,0,0],
    a_position: { buffer: buffers.position, numComponents: 3, },
    a_normal:   { buffer: buffers.normal,   numComponents: 3, },
    a_texcoord: { buffer: buffers.texcoord, numComponents: 2, },
	materialUniforms: {
		u_colorMult:             [1,0,0,1],
		u_diffuse:               textures,
		u_specular:              [1, 0, 1, 1],
		u_shininess:             100,
		u_specularFactor:        0.8,
	}
}

const light={
	u_lightWorldPos:         [0, 0, 555],
	u_lightColor:            [1, 1, 1, 1],
};
var worldUniforms = {
	u_worldViewProjection:   m4.identity(),
	u_world:                 m4.identity(),
	u_worldInverseTranspose: m4.identity(),
};
function degToRad(d) {
    return d * Math.PI / 180;
}

//开始设置着色器变量
// gl.useProgram(program);

// webglUtils.setAttributes(attribSetters, model);//设置模型
// webglUtils.setUniforms(uniformSetters, {
// 	...model.materialUniforms,//设置模型材质
// 	...worldUniforms,//设置世界变量
// 	...light,//设置光
// 	u_viewInverse:camera.matrix//设置视图矩阵u_viewInverse
// });
// gl.drawElements(gl.TRIANGLES, buffers.numElements, gl.UNSIGNED_SHORT, 0);
let t=0
    var adjust;
    var speed = 3;
    var c = t * speed;
    // nodeInfosByName["left-arm" ].rotation[2] = - degToRad(100);//最高
    // nodeInfosByName["left-arm" ].rotation[2] = - degToRad(-90);//最低
    // nodeInfosByName["left-arm" ].rotation[2] = - degToRad(0);//直
    // // nodeInfosByName["left-hand" ].translation[0] -= 0.25;
    // // nodeInfosByName["left-hand" ].translation[1] += 0.5;
    // nodeInfosByName["left-forearm" ].rotation[2] =   degToRad(0);
    // nodeInfosByName["left-forearm" ].rotation[2] =   degToRad(45);
    // nodeInfosByName["left-hand" ].rotation[2] =  degToRad(0);
    // nodeInfosByName["left-hand" ].rotation[2] =  degToRad(45);
    nodeInfosByName["left-arm" ].rotation[2] = - degToRad(-90);//最低
    // nodeInfosByName["left-hand" ].translation[0] -= 0.25;
    // nodeInfosByName["left-hand" ].translation[1] += 0.5;
    nodeInfosByName["left-forearm" ].rotation[2] =   degToRad(0);
    nodeInfosByName["left-hand" ].rotation[2] =  degToRad(0);

    nodeInfosByName["left-arm" ].rotation[0] = - degToRad(-50);//后
    nodeInfosByName["left-arm" ].rotation[0] = - degToRad(50);//前

	
    nodeInfosByName["right-arm" ].rotation[2] = - degToRad(90);//最低
    nodeInfosByName["right-forearm" ].rotation[2] =   degToRad(0);
    nodeInfosByName["right-hand" ].rotation[2] =  degToRad(0);

    nodeInfosByName["right-arm" ].rotation[0] = - degToRad(50);//前
    nodeInfosByName["right-arm" ].rotation[0] = - degToRad(-50);//后


    nodeInfosByName["left-leg" ].rotation[2] = - degToRad(0);//最低
    nodeInfosByName["left-calf" ].rotation[2] =   degToRad(0);
    nodeInfosByName["left-foot" ].rotation[2] =  degToRad(0);

    nodeInfosByName["left-leg" ].rotation[0] = - degToRad(50);//后
    nodeInfosByName["left-leg" ].rotation[0] = - degToRad(-50);//前

	
    nodeInfosByName["right-leg" ].rotation[2] = - degToRad(0);//最低
    nodeInfosByName["right-calf" ].rotation[2] =   degToRad(0);
    nodeInfosByName["right-foot" ].rotation[2] =  degToRad(0);

    nodeInfosByName["right-leg" ].rotation[0] = - degToRad(-50);//后
    nodeInfosByName["right-leg" ].rotation[0] = - degToRad(50);//前
	let step=50
	let leftRight=1
	let thisStep=0
	function move(){
		thisStep+=leftRight*2
		//左手
		nodeInfosByName["right-arm" ].rotation[0] = - degToRad(thisStep);//前
		// 右手
		nodeInfosByName["left-arm" ].rotation[0] = - degToRad(-thisStep);//后
		//左脚
		nodeInfosByName["right-leg" ].rotation[0] = - degToRad(-thisStep);//后
		//右脚
		nodeInfosByName["left-leg" ].rotation[0] = - degToRad(thisStep);//后
			
    	// 	nodeInfosByName["right-arm" ].rotation[0] = - degToRad(-thisStep);//后
    	// 	nodeInfosByName["left-arm" ].rotation[0] = - degToRad(thisStep);//前
		// 	nodeInfosByName["right-leg" ].rotation[0] = - degToRad(thisStep);//前
		// 	nodeInfosByName["left-leg" ].rotation[0] = - degToRad(-thisStep);//前
		// }
		if(Math.abs(thisStep)>step){
			leftRight=leftRight===-1?1:-1
		}
	}
	
function draw(){
	move()//实现了行走
	t+=0.01
{	// camera.position=[
	// 	Math.cos(t)*100,
	// 	0,
	// 	Math.sin(t)*100
	// ]
	
    // adjust = Math.abs(Math.sin(c));
    // nodeInfosByName["机器人关节"].translation[1] = adjust;
    // atimedjust = Math.sin(c);
    // nodeInfosByName["left-leg" ].rotation[0] =  adjust;
    // nodeInfosByName["right-leg"].rotation[0] = -adjust;
    // adjust = Math.sin(c + 0.1) * 0.4;
    // nodeInfosByName["left-calf" ].rotation[0] = -adjust;
    // nodeInfosByName["right-calf"].rotation[0] =  adjust;
    // adjust = Math.sin(c + 0.1) * 0.4;
    // nodeInfosByName["left-foot" ].rotation[0] = -adjust;
    // nodeInfosByName["right-foot"].rotation[0] =  adjust;

    // adjust = Math.sin(c) * 0.4;
    // nodeInfosByName["left-arm" ].rotation[2] =  adjust;
    // nodeInfosByName["right-arm"].rotation[2] =  adjust;
    // adjust = Math.sin(c + 0.1) * 0.4;
    // nodeInfosByName["left-forearm" ].rotation[2] =  adjust;
    // nodeInfosByName["right-forearm"].rotation[2] =  adjust;
    // adjust = Math.sin(c - 0.1) * 0.4;
    // nodeInfosByName["left-hand" ].rotation[2] =  adjust;
    // nodeInfosByName["right-hand"].rotation[2] =  adjust;

    // adjust = Math.sin(c) * 0.4;
    // nodeInfosByName["waist"].rotation[1] =  adjust;
    // adjust = Math.sin(c) * 0.4;
    // nodeInfosByName["torso"].rotation[1] =  adjust;
    // adjust = Math.sin(c + 0.25) * 0.4;
    // nodeInfosByName["neck"].rotation[1] =  adjust;
    // adjust = Math.sin(c + 0.5) * 0.4;
    // nodeInfosByName["head"].rotation[1] =  adjust;
    // adjust = Math.cos(c * 2) * 0.4;
    // nodeInfosByName["head"].rotation[0] =  adjust;
}
	
	scene.updateWorldMatrix()
	//设置相机和投影
	var projectionMatrix =m4.perspective(degToRad(60), gl.canvas.clientWidth / gl.canvas.clientHeight, 1, 2000);
	var cameraMatrix = m4.lookAt(camera.position, camera.target, camera.up, camera.matrix);
	var viewMatrix = m4.inverse(cameraMatrix);
	var viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);
	m4.axisRotate(viewProjectionMatrix,[0,1,0],degToRad(45),viewProjectionMatrix)


	//获取模型在世界的模型位置并转置
	var worldMatrix = m4.translation(...scene.translation);
	worldUniforms.u_world = worldMatrix;
	m4.multiply(viewProjectionMatrix, worldMatrix, worldUniforms.u_worldViewProjection);//和视图矩阵相乘获取u_worldViewProjection
	m4.transpose(m4.inverse(worldMatrix), worldUniforms.u_worldInverseTranspose);

	objects.forEach(function(object) {
		object.drawInfo.uniforms.u_matrix = m4.multiply(viewProjectionMatrix, object.worldMatrix);
		var worldMatrix = m4.translation(...scene.translation);
		object.drawInfo.uniforms.u_worldViewProjection=   m4.identity(),
		object.drawInfo.uniforms.u_worldInverseTranspose= m4.identity(),
		m4.transpose(m4.inverse(object.drawInfo.uniforms.u_matrix,object.drawInfo.uniforms.u_worldInverseTranspose));
		object.drawInfo.uniforms.u_world=object.drawInfo.uniforms.u_matrix
	});
	var lastUsedProgramInfo = null;
	var lastUsedBufferInfo = null;
	// objectsToDraw.forEach(function(object){
	// 	var programInfo = object.programInfo;
	// 	var bufferInfo = object.bufferInfo;
	// 	var bindBuffers = false;
	// 	if (programInfo !== lastUsedProgramInfo) {
	// 		lastUsedProgramInfo = programInfo;
	// 		gl.useProgram(programInfo.program);
	// 		bindBuffers = true;
	// 	}
	// 	if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
	// 		lastUsedBufferInfo = bufferInfo;
	// 		webglUtils.setBuffersAndAttributes(gl, programInfo, bufferInfo);
	// 	}
	// 	webglUtils.setUniforms(programInfo, object.uniforms);
	// 	gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
	// });
	objectsToDraw.forEach(function(object){
		var programInfo = object.programInfo;
		var bufferInfo = object.bufferInfo;
		var bindBuffers = false;
		if (programInfo !== lastUsedProgramInfo) {
			lastUsedProgramInfo = programInfo;
			gl.useProgram(programInfo.program);
			bindBuffers = true;
		}
		if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
			lastUsedBufferInfo = bufferInfo;
			webglUtils.setBuffersAndAttributes(gl, programInfo, bufferInfo);
		}
		
		webglUtils.setUniforms(programInfo.uniformSetters, {
			...light,
			...worldUniforms,//设置世界变量
			u_viewInverse:camera.matrix//设置视图矩阵u_viewInverse
		});
		webglUtils.setUniforms(programInfo, object.uniforms);
		
		gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
	});
	requestAnimationFrame(draw)
}
requestAnimationFrame(draw)
</script>
</body>

</html>